package com.example.demo.controller.mall;

import com.example.demo.entity.Order;
import com.example.demo.entity.Product;
import com.example.demo.entity.member.User;
import com.example.demo.service.SeckillService;
import com.example.demo.service.shop.OrderService;
import com.example.demo.service.shop.ProductService;
import com.example.demo.util.result.Result;
import com.example.demo.util.result.ResultUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Copyright (C), 2019-2019, XXX有限公司
 * FileName: OrderController
 * Author:   longzhonghua
 * Date:     2019/4/15 10:52
 *
 * @Description: $description$
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
@Controller
@RequestMapping("order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;
    @Resource
    private SeckillService seckillService;
    @ApiOperation(value = "跳转到等待秒杀订单创建的页面，秒杀订单是通过MQ异步创建的")
    @GetMapping("/waiting")
    public String waiting(Long productId,Model model) {
        model.addAttribute("productId",productId);
        return "/user/order_waiting";
    }
    @ApiOperation(value = "显示用户个人的订单列表")
    @GetMapping("/orders")
    public String orders(Integer page, Integer size, Model model) {
        String accountName = SecurityContextHolder.getContext().getAuthentication().getName();
        Page<Order> pages = orderService.findByAccount(accountName,page,size);
        model.addAttribute("pages",pages);
        return "/user/order_list";
    }
    @ApiOperation(value = "在等待秒杀订单创建的页面，异步调用该方法获取订单信息，以便去支付方式选择页面")
    @GetMapping("/waitingSeckillOrderCreated/{productId}")
    @ResponseBody
    public Result waitingSeckillOrder(@PathVariable Long productId, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if(user==null) {
            return ResultUtil.error(500,"请先登录");
        }
        //查询redis中该用户秒杀订单的id是否存在
        String orderId = seckillService.getSeckillOrderId(user.getId(),productId);
        if(!StringUtils.isEmpty(orderId)) {
            return ResultUtil.success(200,"订单创建成功",orderId);
        } else {
            return ResultUtil.error(0,"请耐心等待...");
        }
    }
    //在秒杀成功，直接异步创建订单，省略此步骤
//    @ApiOperation(value = "创建秒杀订单,通过发送消息到MQ异步创建订单")
//    @GetMapping("/createSeckillOrder")
//    public String createSeckillOrder(Long productId, Model model) {
//        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        String username = "";
//        User user = null;
//        if(principal instanceof User) {
//            user = (User) principal;
//        } else {
//            username = principal.toString();
//        }
//        if(user == null || "anonymousUser".equals(username)){
//            model.addAttribute("error","请先登录");
//            return "error/error";
//        }
//        //创建秒杀订单（mq)
//        if(!orderService.createSeckillOrder(user.getId(),productId)){
//            model.addAttribute("error","你不是秒杀用户");
//            return "error/error";
//        }
//        //秒杀订单无法及时获取order id，跳转到秒杀订单等待页面
////        model.addAttribute("productId",productId);
//        return "redirect:/order/waiting?productId="+productId;
//    }
    @ApiOperation(value = "创建普通订单")
    @RequestMapping(value = "/createOrder")
    public String createOrder(Order order) throws Exception {
        Product p = productService.findByid(order.getProduct_id());
        order.setStatus(0);
        //价格信息要从库中获取,不然黑客伪造订单,购买虚拟产品就会自动发货
        order.setAmount(p.getPrice());
        orderService.createOrder(order);
        //获取保存后的数据表自增id
        Long order_id = order.getId();
        //传递给支付页面值
        return "redirect:/pay/?order_id=" + order_id;
    }
}
